<?php

namespace App\Controllers;

use CodeIgniter\HTTP\ResponseInterface;

class Home extends BaseController
{
    public function index(): string
    {
        return view('home_index');
    }

    public function login(): string
    {
        return view('home_login');
    }

    public function dash(): string
    {
        return view('home_dash');
    }

    public function user(): string
    {
        return view('home_user');
    }

    public function info()
    {
        phpinfo();
    }

    public function news(): ResponseInterface
    {
        $rules = [
            "page"     => 'if_exist|is_natural_no_zero',
            "pageSize" => 'if_exist|less_than_equal_to[50]',
            "title"    => 'if_exist|string',
            "username" => 'if_exist|string',
        ];

        $errorsMsg = [
            'page'     => [
                'is_natural_no_zero' => '当前页数不能小于1',
            ],
            'pageSize' => [
                'less_than_equal_to' => '分页条数必须少于50',
            ]
        ];

        if (!$this->validate($rules, $errorsMsg)) {
            $errors = $this->validator->getErrors();

            return $this->responseMsg(array_shift($errors));
        }

        $query    = $this->validator->getValidated();
        $page     = intval($query["page"] ?? 1);
        $pageSize = intval($query["pageSize"] ?? 10);

        $builder = db_connect()->table("news")->distinct()->select("title, news.id, summary, news.avatar, user.username, url, publish_time")
            ->join("user", "user.id = news.user_id")->where("publish_time is not null")->where("news.delete_time is null")->orderBy("publish_time", "DESC");

        if (!empty($query["title"])) {
            $builder->like("title", $query["title"]);
        }

        if (!empty($query["username"])) {
            $builder->like("username", $query["username"]);
        }

        $countBuilder = clone $builder;
        $count        = $countBuilder->get()->getNumRows();
        $list         = $builder->get($pageSize, ($page - 1) * $pageSize);

        return $this->responseJson([
            "list"  => $list->getResultObject(),
            "total" => ceil($count / $pageSize),
            "count" => $count,
        ]);
    }
}
